package com.example.util;

import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class GetTokenUtil {


    @Scheduled(cron = "0 0/20 * * * *")
    public String getToken() throws Exception {

        String json = "{\"username\":\"admin\",\"password\":\"ACkj1210\",\"corpId\":\"ding2c7d18eca4ca813eee0f45d8e4f7c288\",\"url\":\"http://agws.rdsh.top/api/login?redirect_uri=http://agws.rdsh.top/api/oauth/authorize?client_id=api&response_type=code&scope=read&redirect_uri=http://agws.rdsh.top/oauth\"}";
        String url = "http://221.3.192.248:8080/api/login/Authentication/get_code";

        String url1 = "http://221.3.192.248:8080/api/login/Authentication/get_token";

        String url_token = "http://agws.rdsh.top/api";
        String client_secret = "c31b32364ce19ca8fcd150a417ecce58";
        String client_id = "api";
        String redirect_uri = "http://agws.rdsh.top/oauth";


        String code = "";
        String access_token = "";
        String refresh_token = "";

        String codeStr = HttpClientUtils.doPostJson(url, json);

        JSONObject jsons = JSONObject.fromObject(codeStr);

        code = jsons.getString("code");

        Map<String, String> param = new HashMap<String, String>();
        param.put("url", url_token);
        param.put("code", code);
        param.put("client_secret", client_secret);
        param.put("client_id", client_id);
        param.put("redirect_uri", redirect_uri);

        try {
            String tokenStr = HttpClientUtils.doGet(url1, param);
            System.out.println("tokenStr"+"================="+tokenStr);
            JSONObject jsonss = JSONObject.fromObject(tokenStr);
            access_token = jsonss.getString("access_token");
            refresh_token = jsonss.getString("refresh_token");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取access_token异常");
        }

        System.out.println(access_token);
        System.out.println(code);

        return access_token;
    }


    public static void main(String[] args) throws Exception {

        GetTokenUtil getTokenUtil = new GetTokenUtil();
        String token = getTokenUtil.getToken();
        System.out.println(token);
    }
}